package com.cellulam.framework.scaffold.generate.db;

import com.cellulam.framework.core.utils.ClassUtil;
import com.google.common.collect.Lists;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ClassUtils;

import java.util.List;

@Getter
@Setter
public class ColumnField {

    private static final List<String> keywords = Lists.newArrayList("class");

    private String columnName;
    private String columnType;
    private String fieldName;
    private Class<?> fieldType;
    private String fieldTypeStr;
    private String fieldTypePrimitiveStr;
    private String javaTypeText;
    @Builder.Default
    private String comment = "";
    @Builder.Default
    private String defaultValue = "";
    private boolean allowNull;

    private boolean pk = false;
    private boolean auto = true;

    public boolean isJson() {
        return "JSON".equalsIgnoreCase(columnType);
    }

    public boolean hasCondition() {

        if (this.columnName.equalsIgnoreCase("is_del")) {
            return false;
        }

//        if ((this.getColumnName().equals("create_time") || this.getColumnName().equals("update_time"))
//                && this.getColumnType().equalsIgnoreCase("timestamp")) {
//            return false;
//        }

        return true;
    }

    public boolean isEnum() {
        return this.comment != null && this.comment.contains("enum");
    }

    public Class<?> getWrapperFieldType() {
        if (fieldType.isPrimitive()) {
            return ClassUtils.primitiveToWrapper(fieldType);
        }
        return fieldType;
    }

    public String getJdbcTypeText() {
        if (!isJson()) {
            return "jdbcType=\"" + columnType + "\"";
        } else {
            return "jdbcType=\"JSON\"";
        }
    }

    public String getJdbcTypeDefText() {
        if (!isJson()) {
            return ",jdbcType=" + columnType + "";
        } else {
            return "";
        }
    }

    public void setFieldType(Class<?> clazz) {
        this.fieldType = clazz;
        this.fieldTypeStr = clazz.getSimpleName();
        this.fieldTypePrimitiveStr = ClassUtil.getPrimitive(clazz).getSimpleName();
    }

    public String getComment() {
        if (keywords.contains(fieldName)) {
            return comment + ", 关键字冲突 后缀加1";
        }
        return comment;
    }

    public String getFieldName() {
        if (keywords.contains(fieldName)) {
            return fieldName + 1;
        }
        return fieldName;
    }

}
